package cn.growthgate.fgo.service.impl;

import java.io.File;
import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.Wrapper;

import cn.growthgate.fgo.common.base.BaseServiceImpl;
import cn.growthgate.fgo.entity.Image;
import cn.growthgate.fgo.entity.vo.ImageVo;
import cn.growthgate.fgo.mapper.ImageMapper;
import cn.growthgate.fgo.service.IImageService;
import cn.growthgate.fgo.util.FileUtils;

/**
 * <p>
 * 图片 服务实现类
 * </p>
 *
 * @author GrowthGate
 * @since 2019-04-21
 */
@Service
public class ImageServiceImpl extends BaseServiceImpl<ImageMapper, Image> implements IImageService {
	
	@Override
	public boolean delete(Wrapper<Image> wrapper) {
		List<Image> images = baseMapper.selectList(wrapper);
		// 删除图片
		images.forEach(image -> FileUtils.delete(new File(image.getPath()), true));
		return super.delete(wrapper);
	}

	@Override
	public Image getByUUID(String uuid) {
		Image image = new Image();
		image.setUuid(uuid);
		return baseMapper.selectOne(image);
	}

	@Override
	public boolean deleteByEntity(String entityName, Long entityId) {
		return delete(newWrapper().eq("entityName", entityName).eq("entityId", entityId));
	}

	@Override
	public ImageVo transformVo(Image image) {
		ImageVo vo = new ImageVo();
		vo.setId(image.getId());
		vo.setUuid(image.getUuid());
		vo.setName(image.getName());
		vo.setPath(image.getPath());
		vo.setLength(image.getLength());
		vo.setHeight(image.getHeight());
		vo.setWidth(image.getWidth());
		vo.setUploadtime(image.getUploadtime());
		vo.setYear(image.getYear());
		vo.setMonth(image.getMonth());
		vo.setDay(image.getDay());
		vo.setUser(baseMapper.getUser(image));
		vo.setEntityName(image.getEntityName());
		vo.setEntityId(image.getEntityId());
		vo.setSize(image.getSize());
		return vo;
	}

	@Override
	public boolean deleteByEntity(String entityName, Long[] entityIds) {
		return delete(newWrapper().eq("entityName", entityName).in("entityId", entityIds));
	}

	@Override
	public boolean deleteByUUID(String uuid) {
		return delete(newWrapper().eq("uuid", uuid));
	}

}
